package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.strategy.SaveOrderStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class SaveOrderStrategyContext implements ApplicationContextAware {

    // Map管理SaveOrderStrategy接口的子类对象, 键：支付方式的取值(1101 , 1103) , 值：SaveOrderStrategy具体的子类对象
    private static Map<String , SaveOrderStrategy> SAVE_ORDER_STRATEGY_MAP = new HashMap<>() ;

    // 根据支付方式获取对应的SaveOrderStrategy的子类对象
    public static SaveOrderStrategy getSaveOrderStrategy(String payType) {
        SaveOrderStrategy saveOrderStrategy = SAVE_ORDER_STRATEGY_MAP.get(payType);
        return saveOrderStrategy ;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, SaveOrderStrategy> beansOfType = applicationContext.getBeansOfType(SaveOrderStrategy.class);
        beansOfType.values().stream().forEach(saveOrderStrategy -> {
            String payWay = saveOrderStrategy.getPayWay();
            SAVE_ORDER_STRATEGY_MAP.put(payWay , saveOrderStrategy) ;
        });
    }

}